<template>
  <div class="mod-user">


    <!-- 手动添加 -->
    <el-dialog width="900px" title="视频预览" :visible.sync="showVideoDialogVisible" :close-on-click-modal="false"
      :close-on-press-escape="false" :append-to-body="true" :modal-append-to-body="false" @close='closeShowVideo'>

      <div class="flex-column justify-center align-center">
        <video v-if="showVideoPath" ref="upvideo" class="avatar video-avatar" controls="controls"
          style="width: 100%;height: 100%;">
          您的浏览器不支持视频播放
        </video>

      </div>
    </el-dialog>

    <el-dialog width="900px;" title="预览" :visible.sync="showPdfDialogVisible" :close-on-click-modal="false"
      :close-on-press-escape="false" :append-to-body="true" :modal-append-to-body="false" @closed="closeShowPdf">
      <pdf-viewer ref="pdfViewer" :src="dialogSrc" :startPage="startPage" :style="{ height: '500px', width: '100%' }"></pdf-viewer>
    </el-dialog>

    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="名称">
        <el-input class="selectWidth" v-model="dataForm.key" placeholder="" clearable></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="tableRef" :data="dataList" :height="height" :header-cell-style="tableHeaderStyle" border
      v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">


      <el-table-column prop="thumbnail" header-align="center" align="center" label="预览" width="190">
        <template slot-scope="scope">
          <img :src="scope.row.thumbnail" alt="" style="width: 160px;height: 80px;">
        </template>
      </el-table-column>
      <el-table-column prop="name" header-align="left" align="left" label="名称">
      </el-table-column>

      <el-table-column prop="size" header-align="center" align="center" label="大小" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.size > 1024">{{ scope.row.size / 1024 }}<span
              v-if="scope.row.size">MB</span></span>
          <span v-else>{{ scope.row.size }}<span v-if="scope.row.size">kb</span></span>
        </template>
      </el-table-column>

      <el-table-column prop="num" header-align="center" align="center" label="关联" width="150">
      </el-table-column>

      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
          <el-button type="text" v-if="scope.row.fileType == 'pdf'" size="small"
            @click="openShowPdf(scope.row)">预览</el-button>

          <el-button type="text" v-else size="small" @click="openShowVideo(scope.row)">预览</el-button>


        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>


  </div>
</template>

<script>
import Hls from 'hls.js';
import pdf from 'vue-pdf'
import pdfViewer from '../../../../src/components/pdf-viewer/pdfh5viewer.vue'
export default {
  components: {
    pdf,
    pdfViewer
  },
  data() {
    return {
      tableHeaderStyle: { background: '#f5f7fa !important', height: '40px !important', padding: '4px !important' },

      height: 0,
      dataForm: {
        key: '',
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      sendCodeVisible: false,
      showVideoPath: "",
      showVideoDialogVisible: false,
      showPdfDialogVisible: false,
      dialogSrc: "",
      startPage: 1


    }
  },
  activated() {
    this.getDataList()
  },
  mounted() {
    console.log(document.body.clientHeight)
    // 至于减去多少，这个要看你的页面高度和你想将滚动轴固定在哪里了，数值可以更换
    this.$nextTick(() => {
      let tableHeight = document.body.clientHeight - 315
      this.height = tableHeight
    })
  },
  methods: {
    openShowPdf(item) {
      console.log(item)
      this.dialogSrc = item.url
      this.showPdfDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.pdfViewer.initPdf( this.dialogSrc )
      })
    },
    openShowVideo(item) {
      this.showVideoPath = item.url
      this.showVideoDialogVisible = true
      this.$nextTick(() => {
        this.playVideo();
      })
    },
    //使用hls.js播放m3u8视频
    playVideo() {
      let video = this.$refs.upvideo;
      if (Hls.isSupported()) {
        var hls = new Hls();
        // 判断是否为m3u8格式然后加载
        if (this.showVideoPath.endsWith('.m3u8')) {
          hls.loadSource(this.showVideoPath);
          hls.attachMedia(video);
          hls.on(Hls.Events.MANIFEST_PARSED, function () {
            video.play();
          });
        } else {
          video.src = this.showVideoPath;
        }
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = this.showVideoPath;
        video.addEventListener('loadedmetadata', function () {
          video.play();
        });
      }
    },
    pauseVideo() {
      let video = this.$refs.upvideo;
      video.pause();
    },
    closeShowVideo() {
      this.showVideoDialogVisible = false
      this.pauseVideo()
    },
    closeShowPdf() {
      this.showPdfDialogVisible = false
    },
    //同步数据
    asyncDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sys/sms/template/save'),
        method: 'get',
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.getDataList()
        } else { }
      })
    },
    repairTable() {
      this.$nextTick(() => {
        // _self.$refs.你的el-table的ref.doLayout()
        this.$refs.tableRef.doLayout()
      })
    },
    // 发送短信
    sendCodeHandle(id) {
      this.sendCodeVisible = true
      this.$nextTick(() => {
        this.$refs.sendCode.init()
      })
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      let search = {
        'page': this.pageIndex,
        'limit': this.pageSize,
        'key': this.dataForm.key,
      }
      this.$http({
        url: this.$http.adornUrl('/sys/oss//list'),
        method: 'get',
        params: this.$http.adornParams(search)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.repairTable()
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(item) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(item)
      })
    },
    //删除
    // 删除
    deleteHandle(id) {
      var userIds = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      this.$confirm(`确定进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/oss/delete'),
          method: 'post',
          data: this.$http.adornData(userIds, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => { })
    }
  }
}
</script>
